package com.vision.sales.cl.ui.component;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.uibinder.client.UiConstructor;
import com.sencha.gxt.data.shared.LabelProvider;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.widget.core.client.form.ComboBox;
import com.vision.core.cl.Callback;
import com.vision.core.cl.ui.UI;
import com.vision.sales.cl.SalesServices;
import com.vision.sales.cl.data.ProductProperties;
import com.vision.sales.cm.db.data.Product;

/**
 * 
 * @author Mark
 *
 */
public class ProductComboBox extends ComboBox<Product> {

	@UiConstructor
	public ProductComboBox() {
		this(new ListStore<Product>(ProductProperties.INSTANCE.key()));
	}

	private ProductComboBox(ListStore<Product> store) {
		super(store, new LabelProvider<Product>() {
			@Override
			public String getLabel(Product item) {
				return item.getCode();
			}
		});
	}
	
	public void loadProducts() {
		UI.mask(this, "Loading products...");
		SalesServices.productSvc().getAll(new Callback<List<Product>>(this) {
			@Override
			protected void handleSuccess(List<Product> result) {
				Collections.sort(result, new Comparator<Product>() {
					@Override
					public int compare(Product arg0, Product arg1) {
						return arg0.getCode().compareToIgnoreCase(arg1.getCode());
					}
				});
				
				getStore().clear();
				getStore().addAll(result);
				
				if (getStore().size() == 1) {
					Scheduler.get().scheduleDeferred(new ScheduledCommand() {
						@Override
						public void execute() {
							select(0);
						}
					});
				}
			}
		});
	}

}
